//app.js
App({
  //地址 
  apiBaseUrl: 'https://dev.banmachewu.com/cgtapi/api',
  apiMsgUrl: 'https://api.banmachewu.com/msg',
  //用户key缓存
  userInfoKey: 'userInfoKey',
  //系统 信息
  systemInfo: {
    model: '', //手机型号
    pixelRatio: '', //像素
    windowWidth: '', //可视窗体宽度
    windowHeight: '', //可视窗体高度
    language: '', //语音
    version: '', //微信版本
    platform: '' //客户端平台
  },
  //用户信息
  userInfo: {
    ThirdUserID: '', //微信openid
    UserID: 0, //用户id
    UserName: '', //用户名称
    SessionKey: '', //用户过期key
    AuthLevel: 0, //用户级别
    UserMobile: '', //电话号码
    ThirdUserName: '', //微信用户昵称
    ThirdUserHead: '' //微信用户头像
  },
  //分享信息
  shareInfo: {
    title: "专用通道不排队，专人服务管全程，专享vip休息室！",
    path: "/pages/index/index",
    imageUrl: "/images/cgt-share.jpg"
  },
  //地址信息
  locationInfo: {
    provinceId: 0, //省份id
    provinceName: '', //省份名称
    cityId: 0, //城市id
    cityName: '' //城市名称
  },
  /**
   * 启动
   */
  onLaunch: function(options) {
    let self = this;

    //可以获取群组信息
    if (options.shareTicket) {
      wx.getShareInfo({
        shareTicket: options.shareTicket,
        success: function(res) {
          wx.showModal({
            title: 'share',
            content: JSON.stringify(res)
          })
        }
      })
    }

    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        let systemInfo = {
          model: res.model,
          pixelRatio: res.pixelRatio,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          language: res.language,
          version: res.version,
          platform: res.platform
        };
        Object.assign(self.systemInfo, systemInfo);
      },
      fail(err) {
        console.log('获取系统信息失败！');
      }
    })

    //缓存读取用户信息
    var strUsrInfo = wx.getStorageSync(self.userInfoKey);
    if (strUsrInfo) {
      self.userInfo = JSON.parse(strUsrInfo);
    }
  },
  //获取用户授权码并添加用户
  addUserAuth(success, fail) {
    let self = this;
    wx.login({
      success: (res) => {
        self.addUserAuthInner(res.code, self.userInfo.ThirdUserID, success);
      },
      fail: (err) => {
        wx.showToast({
          content: '请选择同意授权,否则影响下单', // 文字内容
          type: "none",
          duration: 1500
        });
      },
      complete: function(res) {
        //console.log(res)
      }
    });
  },
  /**
   * 获取用户授权码并添加用户
   */
  addUserAuthInner(authCode, thirdUserID, success) {
    let self = this;
    console.log(self.userInfo)
    //根据授权码进行用户添加
    let url = self.apiBaseUrl + '/WxMini/AddUserInfoByAuthorizationCode';
    self.httpRequest({
      url: url,
      showLoading: false,
      method: "POST",
      data: {
        AuthorizationCode: authCode,
        ThirdUserHead: self.userInfo.ThirdUserHead,
        ThirdUserName: self.userInfo.ThirdUserName,
        ThirdUserID: thirdUserID
      },
      success: function(res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          self.setUserInfo(rdata.data);
          if (success) {
            success(self.userInfo);
          }
        }
      }
    });
  },
  //缓存用户信息
  setUserInfo(usr) {
    let self = this;
    wx.setStorageSync(self.userInfoKey, JSON.stringify(usr));
    self.userInfo = usr;
  },
  //网络请求
  httpRequest(opts) {
    let self = this;
    self.isNetWork();
    if (opts.showLoading) {
      if (opts.method == "POST" || opts.method == "post") {
        //显示加载中
        wx.showLoading({
          title: '提交中...',
          mask: true
        });
      } else {
        //显示加载中
        wx.showLoading({
          title: '加载中...',
          mask: true
        });
      }
    }
    //添加headers
    if (opts.header) {} else {
      opts.header = {};
    }
    opts.header['Content-Type'] = 'application/json';
    for (let k in self.cltInfo) {
      opts.header[k] = self.cltInfo[k]
    }
    //错误提示
    if (opts.fail) {} else {
      //如果错误添加错误日志
      opts.fail = function(res) {
        let d = {
          token: 'wxmini',
          message: res
        };

        wx.request({
          url: self.apiBaseUrl + '/Common/AddErrLog', // 目标服务器 url
          method: "POST",
          data: JSON.stringify(d),
          success: (res) => {

          },
        });
      }
    }

    //微信小程序post参数必须,解析成字符串,官方标准解答
    if (opts.data) {
      if (opts.method == "POST" || opts.method == "post") {
        opts.data = JSON.stringify(opts.data);
      }
    }

    if (opts.complete) {} else {
      opts.complete = function(res) {
        if (opts.showLoading) {
          wx.hideLoading();
        }
      }
    }
    wx.request(opts);
  },
  //必填验证
  isNullOrEmpty(str) {
    if (str) {
      str = str.toString().replace(/^\s+|\s+$/g, '');
      if (str == "null" || str == "") {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  },
  /**
   * 检测网络是否断网
   */
  isNetWork() {
    wx.getNetworkType({
      success: function(res) {
        const networkType = res.networkType;
        if (networkType == 'none' || networkType == 'unknown') {
          wx.navigateTo({
            url: '/pages/networkErr/networkErr',
          })
        }
      }
    })
  }
})